<template>
  <div v-loading="loading">
    <!-- <span @click="setTextColor('#0052d9')">aaa</span> -->
    <textarea ref="textarea" style="height: 600px;"></textarea>
    <span class="wordcount">{{ wordcountLength }} 字</span>
  </div>
</template>

<script>
const regex = /[\s]/g; // 这里包括了空格和一些常见的英文标点符号，你可以根据需要调整这个正则表达式
import tinymce from "tinymce/tinymce";
// import "tinymce/plugins/importcss";
import "./langs/zh_CN.js";
import { getToken } from "@/utils/auth";
import "tinymce/skins/ui/oxide/skin";
import "tinymce/themes/silver/theme";
import "tinymce/icons/default/icons";
import "tinymce/models/dom/model";
import "tinymce/plugins/advlist";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autosave";
import "tinymce/plugins/code";
import "tinymce/plugins/directionality";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/link";
import "tinymce/plugins/anchor";
import "tinymce/plugins/lists";
import "tinymce/plugins/media";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/preview";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/table";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/image";
import "tinymce/plugins/charmap";
// import "tinymce/plugins/autoresize";
import "tinymce/plugins/codesample";
import "tinymce/plugins/directionality";

export default {
  components: {},
  props: {
    value: String,
    cosArg: Object,
    newCos: Object
  },
  data() {
    return {
      editor: null,
      loading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      imgCount: 0,
      urlImg: "",
      wordcountLength: 0,
      contentImage: []
    };
  },
  watch: {
    value: {
      handler() {
        if (this.editor != null) {
          this.setValue(this.value);
        }
      },
      immediate: true
    }
  },
  mounted() {
    tinymce
      .init({
        target: this.$refs.textarea,
        ui_mode: "split",
        language: "zh_CN",
        autosave_ask_before_unload: false,
        paste_data_images: true,
        paste_word_valid_elements: "b,strong,i,em,p,ul,ol,li,a[!href]",
        content_css_cors: true,
        content_style: "img {max-width: 100%; height: auto;}",
        plugins:
          "lists  link  anchor code wordcount image charmap codesample  importcss table visualchars visualblocks searchreplace preview pagebreak nonbreaking   insertdatetime fullscreen directionality autosave autolink advlist",
        toolbar: [
          "undo redo removeformat | bold italic underline strikethrough superscript subscript backcolor forecolor | numlist bullist | blocks | searchreplace fullscreen",
          "fontsize  | alignleft aligncenter alignright alignjustify lineheight outdent indent | image   codesample  | preview "
        ],
        resVideo: "",
        file_picker_types: "media",
        media_live_embed_api_base_url: "",
        media_poster_width: 640,
        media_poster_height: 480,
        media_default_width: 640,
        media_default_height: 480,
        media_dimensions: [640, 480],
        media_dimensions_label: "640x480",
        font_size_formats:
          "9px 10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 36px 42px 48px 72px",
        font_size_input_default_unit: "px",
        paste_preprocess: function(plugin, args) {
          if (args.content) {
            // 处理粘贴内容，例如上传图片到服务器等
            console.log(plugin);
            console.log("Pasted content:", args.content);
          }
        },
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === "media") {
            const that = this;
            const input = document.createElement("input");
            input.setAttribute("type", "file");
            input.setAttribute("accept", ".mp4,.mov,.avi,.webm,image/*");
            input.onchange = function() {
              const file = this.files[0];
              console.log(file);
              that.cosUploadFile(file, callback);
            };
            input.click();
          }
        },

        images_upload_handler: (blobInfo, progress) =>
          new Promise((resolve, reject) => {
            var currentImages = tinymce.activeEditor.dom.select("img");
            const formData = blobInfo.blob();
            const newFile = new File(
              [formData],
              "_zzd_web_" + formData.lastModified,
              { type: formData.type }
            );
            console.log(newFile);
            this.loading = true;
            this.cosUploadFile(newFile, resolve, currentImages.length);
          })
      })
      .then(([editor]) => {
        this.editor = editor;
        editor.on("change input", () => {
          const content = editor.getContent();
          var contentText = editor.getContent({ format: "text" });
          this.imgCount = (content.match(/<img/g) || []).length;
          this.wordcountLength = this.filteredTextLength();
          let data = {
            contentHtml: content,
            contentText: contentText,
            contentImage: []
          };
          var imgMatches = content.match(/<img[^>]+src="([^">]+)"/g);
          if (imgMatches) {
            imgMatches.forEach(function(match) {
              var src = match.split('src="')[1].split('"')[0];
              let imgType = {
                fileUrl: src
              };
              data.contentImage.push(imgType);
              // console.log(src); // 打印每个<img>的src属性
            });
          }
          this.$emit("editorGetContent", data);
        });
      });
  },
  beforeDestroy() {},

  methods: {
    setTextColor(e) {
      tinymce.activeEditor.execCommand("foreColor", true, e);
    },
    getStyleColor() {
      tinymce.activeEditor.on("selectionChange", () => {
        var selectedNode = tinymce.activeEditor.selection.getNode();
        var color = selectedNode.style.color; // 注意：这仅适用于选中的节点，不一定是光标前的内容
        console.log("Selected Node Color:", color);
        // this.setTextColor(color);
        return false;
      });
    },
    clearContent() {
      if (this.editor) {
        // 确保editor已经挂载并可以访问
        this.editor.setContent(""); // 清空内容
      }
    },
    filteredTextLength() {
      // 定义一个正则表达式来匹配空格和常见的标点符号

      // 使用replace方法移除这些字符，然后计算剩余字符串的长度
      return this.editor.getContent({ format: "text" }).replace(regex, "").length;
    },
    setValue(val) {
      if (this.editor != null) {
        this.editor.setContent(val);
      }
    },
    cosUploadFile(file, resolve, length) {
      const then = this;
      try {
        this.newCos.uploadFile(
          {
            Bucket: this.cosArg.bucketName + "-" + this.cosArg.appId,
            Region: this.cosArg.region,
            Key: this.cosArg.fileKey.replace(/\*/g, file.name),
            Body: file,
            onProgress: function(progressData) {
              console.log(progressData);
            },
            onTaskReady: function(id) {}
          },
          function(err, data) {
            var element = document.querySelector(".tox-dialog-wrap");
            if (data) {
              const urlImg = then.cosArg.domain + "/" +then.cosArg.fileKey.replace(/\*/g, file.name);
              if (resolve) {
                if (length <= 10) {
                  resolve(urlImg);
                  then.$message({
                    message: "图片上传成功",
                    type: "success",
                  });
                } else {
                  resolve("");
                  if (element) {
                    element.remove();
                  }
                  then.$message({
                    message: "图片不能超过10张",
                    type: "warning"
                  });
                }
              }
              then.loading = false;
              console.log("图片上传成功", data);
            } else {
              resolve("");
              if (element) {
                element.remove();
              }
              then.$message({
                message: "图片上传失败",
                type: "warning"
              });
              then.loading = false;
              console.log(err, "");
            }
          }
        );
      } catch (e) {
        console.error(e);
      }
    }
  }
};
</script>

<style>
.tox-tinymce {
  min-height: 850px !important;
  border: none !important;
  max-height: 900px;
}

.tox .tox-toolbar__group,
.tox .tox-menubar {
  padding: 0 !important;
}

.tox-tinymce-aux {
  z-index: 10000 !important;
}

.tox .tox-promotion-link {
  display: none !important;
}

.tox .tox-number-input .tox-input-wrapper {
  display: none !important;
}

.tox-statusbar__branding {
  display: none !important;
}

.tox-statusbar__path-item {
  display: none !important;
}

.wordcount {
  position: absolute;
  right: 8px;
  bottom: 8px;
  text-align: right;
  padding: 0 10px;
  color: #666;
}

.tox-statusbar__right-container {
  display: none !important;
}

.mce-content-body {
  overflow-y: auto;
}

.tox-edit-area .tox-edit-area__iframe {
  right: -10px;
}
.tox .tox-dialog-wrap__backdrop {
      background-color: rgba(255, 255, 255, 0);
}
</style>
